import { ActionTree } from 'vuex';
import { UserState } from './typing';
import { RootState } from '@/store/root-state';
import { RESET_CURRENT_USER, SET_USER, SET_ROUTERS, SET_TOKEN, SET_ROUTES, SET_MENU_KEY_MAP, CURRENT_FACTORY } from './mutations';

import {
  LoginParams,
  login,
  loginsso,
  getCurrentUser,
} from '@/api/system/core/login';
import { UserInfo} from '@/api/system/core/typing';
export const LOGIN = 'LOGIN';
export const LOGIN_SSO = 'LOGINSSO';
export const LOGOUT = 'LOGOUT';
export const GET_USER = 'GET_USER';
// export const GENERATE_ROUTES = 'GENERATE_ROUTES';
export const SELECT_KEY = 'SELECT_KEY';

export const actions: ActionTree<UserState, RootState> = {
  [LOGIN]({ commit }, info: LoginParams) {
    return new Promise((resolve, reject) => {
      login(info).then(res => {
        commit(SET_TOKEN, (res.data as UserInfo).token);
        resolve(res.data);
      }).catch(err => reject(err))
    });
  },
  [LOGIN_SSO]({ commit }, info: LoginParams) {
    return new Promise((resolve, reject) => {
      loginsso(info).then(res => {
        commit(SET_TOKEN, (res.data as UserInfo).token);
        resolve(res.data);
      }).catch(err => reject(err))
    });
  },
  [GET_USER]({ commit }) {
    return new Promise((resolve, reject) => {
      getCurrentUser()
        .then((res) => {
          commit(SET_USER, res.data);
          resolve(res);
        }).catch(err => reject(err));
    });
  },
  [LOGOUT]({ commit }) {
    return new Promise(resolve => {
      commit(SET_TOKEN, '');
      commit(RESET_CURRENT_USER);
      resolve(null);
    });
  },
};
